package com.rizhov.iterators;

import com.rizhov.graph.Graph;
import com.rizhov.graph.GraphEdge;
import com.rizhov.gui.MainWindow;

public class GoingOutEdgeIterator implements GraphIterator {

    private Graph graph = Graph.getInstance();
    private int currentOut = -1;
    private boolean isGoneOut = false;

    @Override
    public void next() {
	MainWindow.iteratorStartIndex = -1;
	MainWindow.iteratorEndIndex = -1;
	while (currentOut < graph.getVertexCount()) {
	    currentOut++;
	    if (graph.isEdgeExist(MainWindow.selectedVertexIndex, currentOut)) {
		isGoneOut = false;
		MainWindow.iteratorStartIndex = MainWindow.selectedVertexIndex;
		MainWindow.iteratorEndIndex = currentOut;
		return;
	    }
	}
	isGoneOut = true;
    }

    @Override
    public void setToBegin() {
	MainWindow.iteratorStartIndex = -1;
	MainWindow.iteratorEndIndex = -1;
	currentOut = -1;
	while (currentOut < graph.getVertexCount()) {
	    currentOut++;
	    if (graph.isEdgeExist(MainWindow.selectedVertexIndex, currentOut)) {
		MainWindow.iteratorStartIndex = MainWindow.selectedVertexIndex;
		MainWindow.iteratorEndIndex = currentOut;
		isGoneOut = false;
		return;
	    }
	}
	isGoneOut = true;
    }

    @Override
    public void setToEnd() {
	MainWindow.iteratorStartIndex = -1;
	MainWindow.iteratorEndIndex = -1;
	currentOut = graph.getVertexCount();
	while (currentOut >= 0) {
	    currentOut--;
	    if (graph.isEdgeExist(MainWindow.selectedVertexIndex, currentOut)) {
		MainWindow.iteratorStartIndex = MainWindow.selectedVertexIndex;
		MainWindow.iteratorEndIndex = currentOut;
		isGoneOut = false;
		return;
	    }
	}
	isGoneOut = true;
    }

    @Override
    public void setData(Object newData) {
	String[] strArr = (String[]) newData;
	if (graph.isEdgeExist(MainWindow.selectedVertexIndex, currentOut)) {
	    graph.setEdgeWeight(MainWindow.selectedVertexIndex, currentOut, strArr[0]);
	    graph.setEdgeData(MainWindow.selectedVertexIndex, currentOut, strArr[1]);
	}
    }

    @Override
    public Object getData() {
	if (!isGoneOut) {
	    String[] arr = new String[2];
	    if (graph.isEdgeExist(MainWindow.selectedVertexIndex, currentOut)) {
		arr[0] = graph.getEdgeWeight(MainWindow.selectedVertexIndex, currentOut).toString();
		arr[1] = graph.getEdgeData(MainWindow.selectedVertexIndex, currentOut).toString();
		return arr;
	    } else {
		return null;
	    }
	} else {
	    return null;
	}
    }

    @Override
    public GraphEdge getEdge() {
	if (!isGoneOut) {
	    GraphEdge edge = new GraphEdge();
	    edge.edgeData = ((String[]) getData())[0];
	    edge.edgeWeight = ((String[]) getData())[1];
	    edge.startVertexIndex = MainWindow.selectedVertexIndex;
	    edge.endVertexIndex = currentOut;
	    return edge;
	} else {
	    return null;
	}
    }
}
